#include "model_data_generator.h"
#include "model_data_reader.h"
#include "md_ver_1_0.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>


ModelDataGenerator::ModelDataGenerator(void)
{
}

ModelDataGenerator::~ModelDataGenerator(void)
{
}

int ModelDataGenerator::SaveModelData(ModelData *data, FILE *output)
{
	printf("\nsaving model data...");
	if(data->modelDataVersion == MD_VER_1_0)
	{
		char buff[128];
		memset(buff,0,128);
		MDVer1_0 *modelData = (MDVer1_0 *)data;
		fseek(output,0,SEEK_SET);
		fwrite(buff,0x40,1,output);	//64 bytes reserved

		fseek(output,0,SEEK_SET);
		fwrite(&modelData->modelDataVersion,sizeof(int),1,output);
	
		//starting static data of MD_VER_1_0
		fseek(output,0x10,SEEK_SET);
		fwrite(&modelData->format,sizeof(int),1,output);
		fwrite(&modelData->size,sizeof(int),1,output);
		fwrite(&modelData->totalMeshes,sizeof(int),1,output);

		//starting dynamic data of MD_VER_1_0
		fseek(output,0x40,SEEK_SET);
		fwrite(modelData->meshes,sizeof(MDv1_0_Mesh),modelData->totalMeshes,output);
		fwrite(modelData->data,modelData->stride,modelData->size,output);
		
	}

	return 0; //exit without error
}


ModelData * ModelDataGenerator::SaveModel(char *inputFile, char *outputFile)
{
	//assuming max 5 letter ext is possible
	char *ext = strstr((inputFile + strlen(inputFile) - 5),".");
	ModelData *md = 0;
	FILE *input = fopen(inputFile,"rb");
	if(input != 0)
	{
		FILE *output = fopen(outputFile,"wb");
		if(output != 0)
		{
			if(!strcmp(ext,".obj"))
			{
				md = ReadObjFile(input);
				SaveModelData(md,output);
			}

			fclose(output);
		}
		fclose(input);
	}
	

	return md;

}





int main(int argc, char** argv)
{
	ModelDataGenerator *modelDataGen = new ModelDataGenerator();

	char input[100] = "";
	char output[100] = "";
	
	if(argc >= 2)
	{
		strcpy(input,argv[1]);
		if(argc >=3)
			strcpy(output,argv[2]);
		else
		{
			strcpy(output,input);
			strcat(output,".md");
		}
	}
	//strcpy(input,"../../src/test.obj");
	//strcpy(output,"../../src/test.md");

	printf("\nmodel data converter... %s %s", input,output);
	modelDataGen->SaveModel(input, output);

	delete modelDataGen;
}

